import React, { useState } from 'react';
import './index.less';

export default function GetFieldDeorator(props) {
  const { rules } = props.options;

  const [value, setValue] = useState('');
  const [error, setError] = useState(false);
  const [msg, setMsg] = useState('');
  const validate = (value) => {
    try {
      rules.forEach((rule) => {
        if (rule.required) {
          if (!value) {
            // setMsg(rule.message || '这是一个必填项目');
            throw rule.message || '这是一个必填项目';
          } else {
            setError(false);
            setValue(value);
          }
        } else {
          setError(false);
          setValue(value);
        }
        if (rule.validator) {
          rule.validator(rule, value, (message) => {
            if (message) {
              throw message;
            } else {
              setError(false);
              setValue(value);
            }
          });
        }
      });
    } catch (err) {
      setError(true);
      setMsg(err);
    }
  };

  function getValue() {
    return {
      [props.name]: value,
    };
  }
  return (
    <div className={`ant-form-item-control ${error ? 'has-error' : ''}`}>
      {React.cloneElement(props.children, {
        placeholder: '',
        onChange: (e) => {
          const value = e.target.value;
          validate(value);
        },
      })}
      {error && <div className='ant-form-explain'>{msg}</div>}
    </div>
  );
}
